package com.gao.cluster.config;

import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.ClusterServersConfig;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

@Configuration
public class RedissonConfig {

    /**
     * redisson协议前缀
     */
    private static final String SCHEMA_PREFIX = "redis://";

    @Autowired
    private RedisProperties redisProperties;

    @Bean
    public RedissonClient redissonClient() {
        Config config = new Config();
        RedisProperties.Cluster redisPropertiesCluster  = redisProperties.getCluster();
        //集群redis
        ClusterServersConfig clusterServersConfig = config.useClusterServers();
        for (String cluster : redisPropertiesCluster.getNodes()) {
            clusterServersConfig.addNodeAddress(SCHEMA_PREFIX + cluster);
        }
        if (StringUtils.hasText(redisProperties.getPassword())) {
            clusterServersConfig.setPassword(redisProperties.getPassword());
        }
        clusterServersConfig.setTimeout((int) redisProperties.getTimeout().toMillis());
        clusterServersConfig.setPingConnectionInterval(30000);
        return Redisson.create(config);
    }
}
